import { RedPacketType, useSetting } from "./utils/useSetting"
import { useStorage } from "./utils/useStorage"
declare const JavaAdapter: any;
declare const android: any;

export function renderQiangBao() {
    const setting = useSetting()

    ui.layout(`<LinearLayout  layout_width="match_parent" layout_height="match_parent" orientation="vertical" paddingLeft="4sp" paddingRight="4sp">
    
    <ScrollView layout_width="match_parent" layout_height="wrap_content" paddingTop="4sp">
        <LinearLayout layout_width="match_parent" layout_height="wrap_content" orientation="vertical" paddingTop="4sp">
           
            <TextView layout_width="wrap_content" layout_height="wrap_content" textSize="14sp" text="抓包类型" paddingTop="4sp"/>
            <LinearLayout layout_width="match_parent" layout_height="wrap_content" orientation="vertical" id="type">
                <CheckBox text="穿云箭" id="type_0" checked="${setting.type.includes('穿云箭')}" />
                <CheckBox text="快币" id="type_1" checked="${setting.type.includes('快币')}" />
                <CheckBox text="口令" id="type_2" checked="${setting.type.includes('口令')}" />
                <CheckBox text="粉丝团" id="type_3" checked="${setting.type.includes('粉丝团')}" />
                <CheckBox text="观众包" id="type_4" checked="${setting.type.includes('观众包')}" />
                <CheckBox text="分享" id="type_5" checked="${setting.type.includes('分享')}" />
            </LinearLayout>

            <TextView layout_width="match_parent" layout_height="wrap_content" textSize="14sp" text="分组编号" paddingTop="4sp"/>
            <EditText inputType="number" hint="分组" text="${setting.group}" layout_width="match_parent" layout_height="wrap_content" id="group" />

            <TextView layout_width="match_parent" layout_height="wrap_content" textSize="14sp" text="最小收益率" paddingTop="4sp"/>
            <EditText inputType="number" hint="最小收益率" text="${setting.moneyV}" layout_width="match_parent" layout_height="wrap_content" id="moneyV" />
            
            <button style="Widget.AppCompat.Button.Colored" text="立即开始" id="start"></button>
            <button text="结束应用" id="stop"></button>
        </LinearLayout>
    </ScrollView>
</LinearLayout>`)


    const start = ui.findView("start")
    const stop = ui.findView("stop")
    const root = files.cwd()


    function unique(type: RedPacketType[]) {
        let items: RedPacketType[] = []
        new Set(type).forEach(it => items.push(it))
        return items
    }
    /**
     * 更新抓包类型
     */
    function updateType(id: string, type: RedPacketType) {
        return () => {
            const view = ui.findView(id)
            try {
                if (!Array.isArray(setting.type)) {
                    setting.type = [setting.type]
                }
                const ischecked = setting.type.includes(type)
                if (ischecked) {
                    setting.type = setting.type.filter(it => it !== type)
                } else {
                    setting.type = unique([
                        ...setting.type,
                        type
                    ])
                }
                useStorage().put('setting', setting);
            } catch (e) {
                console.error((e as Error).toString())
            }
        }
    }

    ui.findView('type_0').on('click', updateType('type_0', '穿云箭'))
    ui.findView('type_1').on('click', updateType('type_1', '快币'))
    ui.findView('type_2').on('click', updateType('type_2', '口令'))
    ui.findView('type_3').on('click', updateType('type_3', '粉丝团'))
    ui.findView('type_4').on('click', updateType('type_4', '观众包'))
    ui.findView('type_5').on('click', updateType('type_5', '分享'))

    const textWatcherFactory = (field: string) => JavaAdapter(android.text.TextWatcher, {
        afterTextChanged: function (s: any) { },
        beforeTextChanged: function (s: string, start: number, count: number, after: number) { },
        onTextChanged: function (s: string, start: number, before: number, count: number) {
            try {
                (setting as any)[`${field}`] = parseFloat(s.toString().trim())
                useStorage().put('setting', setting);
            } catch (e) {
                console.error(e)
            }
        }
    })

    const groupTextWatcher = textWatcherFactory('group')
    const moneyVTextWatcher = textWatcherFactory('moneyV')
    ui.findView("group").addTextChangedListener(groupTextWatcher)
    ui.findView("moneyV").addTextChangedListener(moneyVTextWatcher)

    start?.on("click", () => {
        setting.category = '抢包'
        useStorage().put('setting', setting);
        engines.execScriptFile(files.join(root, "task.js"))
        events.emit('start', true)
    })

    stop?.on("click", () => {
        try {
            engines.stopAll()
        } catch (e: any) {
            console.error(e)
        }
    })
}